/*
 * @Date: 2022-02-25 16:37:23
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2022-03-17 11:44:13
 * @FilePath: \gin-antd\server\system\service\SysService\user.go
 */

package SysService

import (
	"go2admin_pure/system/core/db"
	"go2admin_pure/system/core/request"
	"go2admin_pure/system/model/CommonModel"
	"go2admin_pure/system/model/DbModel"
	"go2admin_pure/system/util/sys"
	"gorm.io/gorm"

	"go2admin_pure/system/model/RequestModel"
)

type UserService struct{}

//新增
func (userService *UserService) Add(info *DbModel.SysUser) (err error) {
	info.Password = sys.EncryptPass(info.Password)
	result := db.Instance().Create(info)
	return result.Error
}

//修改
func (userService *UserService) Update(info *DbModel.SysUser) (err error) {
	var user DbModel.SysUser
	if err := db.Instance().First(&user, info.ID).Error; err != nil {
		return err
	}
	info.Password = sys.EncryptPass(info.Password)
	//忽略字段
	if info.Password == "" {
		return db.Instance().Omit("CreatedAt", "Password").Save(info).Error
	} else {
		return db.Instance().Omit("CreatedAt").Save(info).Error
	}

}

//分页列表
func (userService *UserService) List(info RequestModel.SysUserSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	db := db.Instance().Model(&DbModel.SysUser{})
	//动态查询条件
	request.GenWhere(info, db)
	var userList []DbModel.SysUser
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&userList).Error
	return err, userList, total
}

//删除
func (userService *UserService) Remove(info CommonModel.Ids) (err error) {

	return db.Instance().Transaction(func(tx *gorm.DB) error {
		// 使用 'tx' 而不是 'db'
		if err := tx.Where("user_id in ?", info.Ids).Delete(&DbModel.SysUserRole{}).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		if err := tx.Where("user_id in ?", info.Ids).Delete(&DbModel.SysUserPermission{}).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		if err := tx.Delete(&DbModel.SysUser{}, info.Ids).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 返回 nil 提交事务
		return nil
	})

}

//获取已经具备的权限
func (userService *UserService) Permissions(id uint) (err error, list interface{}) {
	var dataList []DbModel.SysUserPermission
	err = db.Instance().Preload("Permission").Where("user_id = ?", id).Find(&dataList).Error
	return err, dataList
}

//分配权限
func (userService *UserService) SetPermissions(r RequestModel.SysSetPermissions) (err error) {
	var dataList []DbModel.SysUserPermission
	for _, v := range r.CheckedKeys {
		dataList = append(dataList, DbModel.SysUserPermission{UserId: r.Id, PermissionId: v, Checked: 1})
	}
	for _, v := range r.HalfCheckedKeys {
		dataList = append(dataList, DbModel.SysUserPermission{UserId: r.Id, PermissionId: v, Checked: 0})
	}

	return db.Instance().Transaction(func(tx *gorm.DB) error {
		// 使用 'tx' 而不是 'db'
		if err := tx.Where("user_id = ?", r.Id).Delete(&DbModel.SysUserPermission{}).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		if len(dataList) > 0 {
			if err := tx.Create(&dataList).Error; err != nil {
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
}

//获取已经分配角色
func (userService *UserService) Roles(id uint) (err error, list interface{}) {
	var dataList []DbModel.SysUserRole
	err = db.Instance().Preload("Roles").Where("user_id = ?", id).Find(&dataList).Error
	return err, dataList
}

//给用户分配角色
func (userService *UserService) SetRoles(r RequestModel.SysSetRoles) (err error) {

	var dataList []DbModel.SysUserRole
	for _, v := range r.Roles {
		dataList = append(dataList, DbModel.SysUserRole{UserId: r.Id, RoleId: v})
	}

	return db.Instance().Transaction(func(tx *gorm.DB) error {
		// 使用 'tx' 而不是 'db'
		if err := tx.Where("user_id  = ?", r.Id).Delete(&DbModel.SysUserRole{}).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		if len(dataList) > 0 {
			if err := tx.Create(&dataList).Error; err != nil {
				return err
			}
		}

		// 返回 nil 提交事务
		return nil
	})

}
